package xjwt

import (
	"github.com/golang-jwt/jwt/v4"
	"time"
)

type TokenOptions struct {
	SecretKey string
	Payloads  TokenData
	Iat       int64
	Seconds   int64
}

type TokenData struct {
	UserId    int64
	UserType  string
	UserLevel int64
	Province  string
	City      string
	Area      string
	Mobile    string
}

// GenToken 生成token
func GenToken(options TokenOptions) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = options.Iat + options.Seconds
	claims["iat"] = options.Iat
	claims["userid"] = options.Payloads.UserId
	claims["userType"] = options.Payloads.UserType
	claims["userLevel"] = options.Payloads.UserLevel
	claims["province"] = options.Payloads.Province
	claims["city"] = options.Payloads.City
	claims["area"] = options.Payloads.Area
	claims["mobile"] = options.Payloads.Mobile
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims

	return token.SignedString([]byte(options.SecretKey))
}

// ParseToken 解析token
func ParseToken(tokenString, secretKey string) (*TokenData, error) {
	var mapClaims jwt.MapClaims
	_, err := jwt.ParseWithClaims(tokenString, &mapClaims, func(token *jwt.Token) (interface{}, error) {
		return []byte(secretKey), nil
	})
	if err != nil {
		return nil, err
	}

	return &TokenData{
		UserId:    mapClaims["uid"].(int64),
		UserType:  mapClaims["userType"].(string),
		UserLevel: mapClaims["userLevel"].(int64),
		Province:  mapClaims["province"].(string),
		City:      mapClaims["city"].(string),
		Area:      mapClaims["area"].(string),
	}, nil
}

func GetTimeNow() int64 {
	return time.Now().Unix()
}
